package com.black.app.service.impl.store;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.req.store.add.AppStoreCategoryAddReq;
import com.black.app.domain.req.store.edit.AppStoreCategoryEditReq;
import com.black.app.domain.req.store.query.AppStoreCategoryQueryReq;
import com.black.app.domain.resp.store.*;
import com.black.app.domain.store.AppStoreCategory;
import com.black.app.domain.store.AppStoreProductSpecifications;
import com.black.app.service.store.AppStoreCategoryService;
import com.black.app.mapper.store.AppStoreCategoryMapper;
import com.black.app.service.store.AppStoreProductSpecificationsService;
import com.black.app.service.store.AppStoreProductsService;
import com.black.common.exception.ServiceException;
import com.black.common.exception.database.PrimaryException;
import com.black.common.exception.database.RecordNotFoundException;
import com.black.common.utils.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author 12572
* @description 针对表【app_store_category】的数据库操作Service实现
* @createDate 2024-10-28 08:58:44
*/
@Service
public class AppStoreCategoryServiceImpl extends ServiceImpl<AppStoreCategoryMapper, AppStoreCategory>
    implements AppStoreCategoryService{

    private final AppStoreProductsService appStoreProductsService;

    @Autowired
    public AppStoreCategoryServiceImpl(@Lazy AppStoreProductsService appStoreProductsService) {
        this.appStoreProductsService = appStoreProductsService;
    }

    @Autowired
    private AppStoreProductSpecificationsService appStoreProductSpecificationsService;

    @Override
    public List<AppStoreCategoryResp> search() {
        //查询到数据库的数据
        List<AppStoreCategory> catelist = this.baseMapper.search();

        //递归组装树型结构
        return getAppStoreCategoryResps(catelist);
    }

    @Override
    public List<AppStoreCategoryTreeResp> tree() {
        List<AppStoreCategory> categories = this.baseMapper.tree();
        List<AppStoreCategoryTreeResp> cateTreeList = this.buildTree(categories);
        return cateTreeList;
    }

    @Override
    public AppStoreCategoryResp findById(Integer id) {
        if (Objects.isNull(id)){
            throw new PrimaryException();
        }
        AppStoreCategory category = this.getById(id);

        if (Objects.isNull(category)){
            throw new RecordNotFoundException();
        }
        AppStoreCategoryResp resp = new AppStoreCategoryResp(category);
        BeanUtils.copyProperties(category,resp);
        return resp;

    }

    @Override
    public boolean add(AppStoreCategoryAddReq req) {
        //校验当前父级分类中是否存在新增的子分类
        if (this.baseMapper.exists(new LambdaQueryWrapper<AppStoreCategory>().eq(AppStoreCategory::getCategoryName, req.getCategoryName()))){
            throw new ServiceException(MessageUtils.message("sysdept.categoryName.exists"));
        }
        AppStoreCategory category = new AppStoreCategory();
        BeanUtils.copyProperties(req,category);
        return this.save(category);
    }

    @Override
    public boolean deleteById(Long id) {
        if (Objects.isNull(id)) {
            throw new PrimaryException();
        }

        // 根据主键查询，是否存在
        AppStoreCategory category = this.getById(id);
        if (Objects.isNull(category)) {
            throw new RecordNotFoundException();
        }
        return this.removeById(id);
    }

    @Override
    public List<AppStoreProductsTreeResp> homeStoreTree() {
        //查询所有分类
        List<AppStoreCategory> cateList = this.baseMapper.search();
        List<AppStoreProductsTreeResp> AppStoreTreetypeList = buildTrees(cateList);
        return AppStoreTreetypeList;
    }

    @Override
    public boolean edit(AppStoreCategoryEditReq req) {
        //根据主键查询
        AppStoreCategory appStoreCategory = this.getById(req.getCategoryId());
        if (Objects.isNull(appStoreCategory)){
            throw new RecordNotFoundException();
        }
        //校验分类名称是否已存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<AppStoreCategory>().eq(AppStoreCategory::getCategoryName, req.getCategoryName()).ne(AppStoreCategory::getCategoryId, req.getCategoryId()))){
            throw new ServiceException(MessageUtils.message("appstorecategory.categoryName.exists"));
        }
        BeanUtils.copyProperties(req,appStoreCategory);

        boolean res = this.updateById(appStoreCategory);
        return res;
    }

    @Override
    public PageInfo<AppStoreCategory> paginationQuery(AppStoreCategoryQueryReq req) {
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            this.baseMapper.paginationQuery(req);
        });
    }

    private List<AppStoreProductsTreeResp> buildTrees(List<AppStoreCategory> cateList) {
        List<AppStoreProductsTreeResp> typeTreeRespList = new ArrayList<>();
        cateList.stream()
                .filter(item->item.getSuperId().intValue() == 0).forEach(item-> {
            AppStoreProductsTreeResp AppStoreTreeResp = new AppStoreProductsTreeResp();
            AppStoreTreeResp.setSuperId(item.getSuperId());
            AppStoreTreeResp.setCategoryId(item.getCategoryId());
            AppStoreTreeResp.setCategoryName(item.getCategoryName());
            AppStoreTreeResp.setCategoryImageSrc(item.getCategoryImageSrc());

            buidChildrenTree(AppStoreTreeResp, cateList);

            typeTreeRespList.add(AppStoreTreeResp);



        });
        return typeTreeRespList;
    }

    private void buildChildrenTrees(AppStoreProductsTreeResp appStoreTreeResp) {
        /*List<AppStoreProductsResp> list = this.appStoreProductsService.findByCidAll(appStoreTreeResp.getCategoryId());
        list.forEach(item->{
            AppStoreProductsResp children = new AppStoreProductsResp();
            children.setProductId(item.getProductId());

            buildChildrenSpecificationList(children);
            list.add(children);
        });

        appStoreTreeResp.setChildren(list);*/
        List<AppStoreProductsResp> childrenList = new ArrayList<>();
        List<AppStoreProductsResp> list = this.appStoreProductsService.findByCidAll(appStoreTreeResp.getCategoryId());

        list.forEach(item -> {
            AppStoreProductsResp children = new AppStoreProductsResp();
            children.setProductId(item.getProductId());
            children.setProductName(item.getProductName());
            children.setImageUrl(item.getImageUrl());
            children.setDetail(item.getDetail());
            children.setProductPrice(item.getProductPrice());
            children.setIsDiscount(item.getIsDiscount());
            children.setInventory(item.getInventory());
            children.setCategoryId(item.getSuperId());
            children.setSuperId(item.getSuperId());
            children.setSuperId(item.getSuperId());
            children.setCategoryId(item.getCategoryId());

            buildChildrenSpecificationList(children);
            childrenList.add(children);
        });

        appStoreTreeResp.setChildren(childrenList);
    }

    private void buildChildrenSpecificationList(AppStoreProductsResp list) {
        List<AppStoreProductSpecifications> appStoreProductSpecificationsList = this.appStoreProductSpecificationsService.findByPidAll(list.getProductId());
        list.setSpecificationList(appStoreProductSpecificationsList);

    }

    private void buidChildrenTree(AppStoreProductsTreeResp appStoreTreeResp, List<AppStoreCategory>cateList) {
        List<AppStoreProductsTreeResp> childrenList = new ArrayList<>();
        cateList.stream().filter(item->item.getSuperId().intValue() == appStoreTreeResp.getCategoryId().intValue()).forEach(item->{
            AppStoreProductsTreeResp children = new AppStoreProductsTreeResp();
            children.setSuperId(item.getSuperId());
            children.setCategoryId(item.getCategoryId());
            children.setCategoryName(item.getCategoryName());
            children.setCategoryImageSrc(item.getCategoryImageSrc());

            buidChildrenTree(children,cateList);

            buildChildrenTrees(children);



            childrenList.add(children);


        });
        //有子节点，才加入到上级节点中
        if (childrenList.size()>0){
            appStoreTreeResp.setChildrens(childrenList);
        }

    }



    private List<AppStoreCategoryTreeResp> buildTree(List<AppStoreCategory> categories) {
        List<AppStoreCategoryTreeResp> TreeList = new ArrayList<>();

        categories.stream().filter(p -> p.getSuperId().intValue() == 0).forEach(item -> {
            AppStoreCategoryTreeResp root = new AppStoreCategoryTreeResp();
            root.setCategoryId(item.getCategoryId());
            root.setCategoryName(item.getCategoryName());
            buildChildrenTypeTree(root, categories);
            TreeList.add(root);
        });
        return TreeList;
    }

    private void buildChildrenTypeTree(AppStoreCategoryTreeResp root, List<AppStoreCategory> categories) {
        List<AppStoreCategoryTreeResp> childrenList = new ArrayList<>();
        // 查询子节点
        categories.stream().filter(p -> p.getSuperId().intValue() == root.getCategoryId().intValue()).forEach(item -> {
            AppStoreCategoryTreeResp children = new AppStoreCategoryTreeResp();
            children.setCategoryId(item.getCategoryId());
            children.setCategoryName(item.getCategoryName());
            // 递归构建子节点
            buildChildrenTypeTree(children, categories);
            childrenList.add(children);
        });
        // 有子节点，才加入到上级节点中
        if (childrenList.size() > 0) {
            root.setChildren(childrenList);
        }

    }

    private List<AppStoreCategoryResp> getAppStoreCategoryResps(List<AppStoreCategory> catelist) {
        //递归组装树型结构
        List<AppStoreCategoryResp> treeCategoryList = new ArrayList<>();

        //得到所有的category_id
        List<Integer> tempList = catelist.stream().map(AppStoreCategory::getCategoryId).collect(Collectors.toList());

        for (AppStoreCategory category : catelist) {
            // 如果是顶级节点， 遍历该父节点的所有子节点
            if (!tempList.contains(category.getSuperId())) {
                AppStoreCategoryResp parentCat =  new AppStoreCategoryResp(category);
                // 递归获取子节点
                getChildList(catelist, parentCat);
                // 添加到最终结果中
                treeCategoryList.add(parentCat);
            }
        }

        if (treeCategoryList.isEmpty()){
            treeCategoryList = catelist.stream().map(AppStoreCategoryResp::new).collect(Collectors.toList());
        }

        return treeCategoryList;
    }

    private void getChildList(List<AppStoreCategory> catelist, AppStoreCategoryResp parentCat) {
        // 子节点
        List<AppStoreCategoryResp> childrenList = new ArrayList<>();
        // 遍历所有节点，将父节点与子节点匹配
        catelist.stream().filter(item -> item.getSuperId().equals(parentCat.getCategoryId())).forEach(item -> {
            AppStoreCategoryResp child = new AppStoreCategoryResp(item);
            // 递归查询子节点
            getChildList(catelist, child);

            childrenList.add(child);
        });

        if (!childrenList.isEmpty()) {
            parentCat.setChildren(childrenList);
        }

    }

}




